package com.etxxy.common.webservice;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import org.codehaus.xfire.client.Client;
import org.codehaus.xfire.transport.http.CommonsHttpMessageSender;

/**
 * @category Xfire 操作webservice
 * 
 * @author yiz
 * @date 2016年5月11日 上午11:46:44
 * @version 1.0.0 
 * @copyright pycredit.cn 
 */
public class XFireClientUtil {

	private static final int TIMEOUT = 20000;

	private static final String DISABLE_KEEP_ALIVE = "true";

	private static final String DISABLE_EXPECT_CONTINUE = "true";

	private static Client getClint(HttpURLConnection connection) throws IOException, Exception {
		Client client = new Client(connection.getInputStream(), null);
		client.setProperty(CommonsHttpMessageSender.HTTP_TIMEOUT, TIMEOUT);
		client.setProperty(CommonsHttpMessageSender.DISABLE_KEEP_ALIVE, DISABLE_KEEP_ALIVE);
		client.setProperty(CommonsHttpMessageSender.DISABLE_EXPECT_CONTINUE, DISABLE_EXPECT_CONTINUE);
		return client;
	}

	public static Object[] callAuthService(String serviceUrl, String serviceName, String username, String password,
			Object... params) throws Exception {
		URL url = new URL(serviceUrl);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setConnectTimeout(TIMEOUT);
		connection.setReadTimeout(TIMEOUT);
		connection.connect();

		int code = connection.getResponseCode();
		//连接成功，返回200状态
		if (code == HttpURLConnection.HTTP_OK) {
			Client client = getClint(connection);
			client.addOutHandler(new ClientAuthHandler(username, password));
			return client.invoke(serviceName, params);
		}
		throw new Exception("连接出现错误code=" + code);
	}
}
